<template>
  <el-dialog
    :title="isAdd ? '添加商品管理' : '编辑商品管理'"
    :visible.sync="isShow"
    center
    :before-close="cancel"
    :modal="false"
    @opened="Description"
  >
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item
        prop="first_cateid"
        label="一级分类"
        :label-width="formLabelWidth"
      >
        <el-select
          @change="changecate(false)"
          v-model="form.first_cateid"
          placeholder="请选择"
        >
          <el-option
            v-for="item in catelist"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="second_cateid"
        label="二级分类"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.second_cateid" placeholder="请选择">
          <el-option
            v-for="item in secondCateid"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="goodsname"
        label="商品名称"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.goodsname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
        <el-input v-model.number="form.price" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        prop="market_price"
        label="市场价格"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model.number="form.market_price"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth">
        <el-upload
          action="#"
          list-type="picture-card"
          :on-preview="onPreview"
          :on-remove="onRemove"
          :on-change="onChange"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :modal-append-to-body="false" :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item
        prop="specsid"
        label="商品规格"
        :label-width="formLabelWidth"
      >
        <el-select
          @change="changespecs(false)"
          v-model="form.specsid"
          placeholder="请选择"
        >
          <el-option
            v-for="item in specslist"
            :key="item.id"
            :value="item.id"
            :label="item.specsname"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="specsattr"
        label="规格属性"
        :label-width="formLabelWidth"
      >
        <el-select multiple v-model="form.specsattr" placeholder="请选择">
          <el-option
            v-for="item in specsAttr"
            :key="item"
            :value="item"
            :label="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否新品" :label-width="formLabelWidth">
        <el-radio v-model="form.isnew" :label="1">是</el-radio>
        <el-radio v-model="form.isnew" :label="2">否</el-radio>
      </el-form-item>
      <el-form-item label="是否热卖" :label-width="formLabelWidth">
        <el-radio v-model="form.ishot" :label="1">是</el-radio>
        <el-radio v-model="form.ishot" :label="2">否</el-radio>
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-switch
          v-model="form.status"
          active-color="#409EFF"
          inactive-color="#DCDFE6"
          :active-value="1"
          :inactive-value="2"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="商品描述" :label-width="formLabelWidth">
        <div id="description"></div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="comfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { goodsAdd, goodsInfo, goodsEdit } from "@/request/api";
import { mapActions, mapGetters } from "vuex";
import E from "wangeditor";
export default {
  props: ["isShow", "isAdd"],
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      form: {
        first_cateid: "", // 一级分类编号
        second_cateid: "", // 二级分类编号
        goodsname: "", //商品名称
        price: "", // 商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", // 商品规格编号
        specsattr: "", // 商品规格属性
        isnew: 1, // 是否新品     1-是 2-否
        ishot: 1, // 是否热卖推荐 1-是 2-否
        status: 1, //  状态1正常2禁用
      },
      formLabelWidth: "120px",
      secondCateid: [], //二级分类
      specsAttr: [], // 商品规格属性
      description: null, //编辑器
      rules: {
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请填写商品价格" },
          { type: "number", message: "价格必须为数字值" },
        ],
        market_price: [
          { required: true, message: "请填写市场价格" },
          { type: "number", message: "价格必须为数字值" },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        specsattr: [
          { required: true, message: "请选择规格属性", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      catelist: "cate/getCateList",
      specslist: "specs/getSpecslist",
    }),
  },
  mounted() {
    this.getCate();
    this.getSpecs();
  },
  methods: {
    Description() {
      // console.log("打开弹框");
      this.description = new E("#description");
      this.description.create();
      this.description.txt.html(this.form.description);
      console.log(this.description, "编辑器");
    },
    ...mapActions({
      getCate: "cate/changeCateAction",
      getSpecs: "specs/changeSpecsListAction",
      getGoods: "goods/changeGoodsListAction",
      getCount: "goods/changeCountAction",
    }),
    lookup(id) {
      goodsInfo({
        id,
      }).then((res) => {
        console.log(res, "获取一条数据");
        if (res.code == 200) {
          this.form = res.list;
          this.form.id = id;
          this.fileList = this.form.img ? [{ url: this.form.img }] : [];
          this.form.specsattr = this.form.specsattr.split(",");
          this.description.txt.html(this.form.description);
          this.changecate(true);
          this.changespecs(true);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    changecate(n) {
      // console.log(this.form.first_cateid, "changecatechangecate");
      let index = this.catelist.findIndex(
        (item) => item.id == this.form.first_cateid
      );
      // console.log(index, "index");
      this.secondCateid = this.catelist[index].children;
      if (!n) {
        this.form.second_cateid = "";
      }
    },
    changespecs(n) {
      // console.log(this.form.specsid, "changespecschangespecs");
      let index = this.specslist.findIndex(
        (item) => item.id == this.form.specsid
      );
      // console.log(index);
      this.specsAttr = this.specslist[index].attrs;
      if (!n) {
        this.form.specsattr = "";
      }
    },
    onRemove(file, fileList) {
      console.log(file, fileList);
    },
    onPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onChange(file, filelist) {
      console.log(file, filelist, "change");
      this.form.img = file.raw;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    reset() {
      this.form = {
        first_cateid: "", // 一级分类编号
        second_cateid: "", // 二级分类编号
        goodsname: "", //商品名称
        price: "", // 商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", // 商品规格编号
        specsattr: "", // 商品规格属性
        isnew: 1, // 是否新品     1-是 2-否
        ishot: 1, // 是否热卖推荐 1-是 2-否
        status: 1, //  状态1正常2禁用
      };
      this.$refs.form.resetFields();
      this.fileList = [];
      this.description.destroy();
    },
    cancel() {
      this.$emit("cancel", false);
      this.reset();
    },
    comfirm() {
      this.$refs.form.validate((flag) => {
        if (flag) {
          console.log(this.form, "表单对象");
          this.form.specsattr = this.form.specsattr
            ? this.form.specsattr.join(",")
            : "";
          this.form.description = this.description.txt.html();
          if (this.isAdd) {
            // 商品管理添加
            goodsAdd(this.form).then((res) => {
              console.log(res, "商品管理添加");
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getGoods();
                this.getCount();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            // 商品管理编辑
            goodsEdit(this.form).then((res) => {
              console.log(res, "商品管理编辑");
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getGoods();
                this.getCount();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          alert("验证失败");
        }
      });
    },
  },
};
</script>

<style lang="less"scoped>
</style>
